"""
监控指标相关路由模块

该模块提供监控指标相关的API端点，用于接收agent上报的监控数据。
"""

from fastapi import APIRouter, Depends, HTTPException, status
from typing import Dict, Any
from app.schemas.response import ApiResponse
from app.schemas.metric import AgentConfig
from app.services.metric_service import MetricService
from app.core.deps import get_db
from sqlalchemy.orm import Session
import logging
from datetime import datetime

logger = logging.getLogger(__name__)

router = APIRouter()

@router.post("/agent-report", response_model=ApiResponse)
async def receive_agent_data(
    agent_data: Dict[str, Any],
    db: Session = Depends(get_db)
):
    """接收agent上报的监控数据
    
    Args:
        agent_data (Dict[str, Any]): 来自agent的监控数据
        db (Session): 数据库会话对象，通过依赖注入提供
        
    Returns:
        ApiResponse: 响应结果
    """
    metric_service = MetricService(db)
    success = metric_service.process_agent_data(agent_data)
    
    if success:
        return ApiResponse(
            success=True,
            message="监控数据接收成功"
        )
    else:
        return ApiResponse(
            success=False,
            message="监控数据处理失败"
        )

@router.get("/agent-config", response_model=ApiResponse)
async def get_agent_config(
    machine_ip: str,
    db: Session = Depends(get_db)
):
    """获取agent配置信息
    
    Args:
        machine_ip (str): 机器IP地址
        db (Session): 数据库会话对象，通过依赖注入提供
        
    Returns:
        ApiResponse: 包含agent配置的响应
    """
    metric_service = MetricService(db)
    config_data = metric_service.get_agent_config(machine_ip)
    
    if not config_data:
        return ApiResponse(
            success=False,
            message=f"未找到IP地址为 {machine_ip} 的机器或获取配置失败"
        )
    
    # 构造配置信息
    config = AgentConfig(
        machine_id=config_data['machine_id'],
        interval=config_data.get('interval', 30),
        collect_system_info=config_data.get('collect_system_info', True),
        collect_cpu_info=config_data.get('collect_cpu_info', True),
        collect_memory_info=config_data.get('collect_memory_info', True),
        collect_disk_info=config_data.get('collect_disk_info', True),
        collect_network_info=config_data.get('collect_network_info', True),
        collect_process_info=config_data.get('collect_process_info', False),
        collect_log_info=config_data.get('collect_log_info', False),
        collect_database_info=config_data.get('collect_database_info', False),
        log_paths=config_data.get('log_paths', []),
        database_configs=config_data.get('database_configs', []),
        port_list=config_data.get('port_list', []),
        process_names=config_data.get('process_names', [])  # 添加process_names字段
    )
    
    return ApiResponse(
        success=True,
        data=config.dict(),
        message="配置获取成功"
    )

@router.put("/agent-config/{machine_id}", response_model=ApiResponse)
async def update_agent_config(
    machine_id: int,
    config: AgentConfig,
    db: Session = Depends(get_db)
):
    """更新agent配置信息
    
    Args:
        machine_id (int): 机器ID
        config (AgentConfig): 新的配置信息
        db (Session): 数据库会话对象，通过依赖注入提供
        
    Returns:
        ApiResponse: 更新结果响应
    """
    metric_service = MetricService(db)
    success = metric_service.update_agent_config(machine_id, config.dict())
    
    if success:
        return ApiResponse(
            success=True,
            message="配置更新成功"
        )
    else:
        return ApiResponse(
            success=False,
            message="配置更新失败"
        )

@router.get("/machines/{machine_id}", response_model=ApiResponse)
async def get_machine_metrics(
    machine_id: int,
    db: Session = Depends(get_db)
):
    """获取指定机器的监控指标历史数据
    
    Args:
        machine_id (int): 机器ID
        db (Session): 数据库会话对象，通过依赖注入提供
        
    Returns:
        ApiResponse: 包含监控指标历史数据的响应
    """
    from app.crud.metric import get_metrics_by_machine_id
    metrics = get_metrics_by_machine_id(db, machine_id)
    return ApiResponse(
        success=True,
        data=[metric.__dict__ for metric in metrics]
    )